package com.cellulam.framework.core.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.Collection;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

public final class TextUtils {

    private static final char BRACE_START = '{';

    private static final char BRACE_END = '}';

    public static final String randomStr(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static final <E> String join(Collection<E> collection) {
        return join(",", collection);
    }

    public static final <E> String join(CharSequence delimiter, Collection<E> collection) {
        if (CollectionUtils.isEmpty(collection)) {
            return null;
        }

        return collection.stream()
                .map(x -> x.toString())
                .collect(Collectors.joining(delimiter));
    }

//    private static final Pattern BRACE_PATTERN = Pattern.compile("\\{}");


    /**
     * 转换一个对象为可用的字符串: <br>
     * 1) null -> "NULL" <br>
     * 2) String -> String <br>
     * 3) 简单类型 -> String <br>
     * 4) 其他 -> 都用json序列化
     *
     * @param value
     * @return
     */
    public static String valueToText(Object value) {
        String text = "";
        if (value == null) {
            text = "";
        } else {
            if (value instanceof String) {
                text = (String) value;
            } else if (BeanUtils.isSimpleValueType(value.getClass())) {
                text = String.valueOf(value);
            } else if (value instanceof byte[]) {
                text = new String((byte[]) value);
            } else {
                text = JacksonUtils.toJson(value);
            }
        }
        return text;
    }

    /**
     * 用参数替换文本中的 {}
     *
     * @param msg
     * @param params
     * @return
     */
    public static String format(String msg, Object... params) {
        if (StringUtils.isEmpty(msg)) {
            return msg;
        }

        if (params == null || params.length == 0) {
            return msg;
        }

        // 使用简单替换
        char[] arr = msg.toCharArray();
        int paramLen = params.length;
        int charLen = arr.length;

        int pIdx = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < charLen; i++) {
            char ch = arr[i];
            if (i >= (charLen - 1)) {// 最后一个字符
                sb.append(ch);
                continue;
            }

            if (pIdx < paramLen && ch == BRACE_START) {// 字符 == {
                if (arr[++i] == BRACE_END) {// 下一个字符 == }
                    sb.append(params[pIdx]);
                    pIdx++;
                } else {
                    sb.append(BRACE_START).append(arr[i]);
                }
                continue;
            }

            sb.append(ch);
        }

        return sb.toString();
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String compress(String text) {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c != '\r'
                    && c != '\n'
                    && c != '\t'
                    && c != ' ') {
                stringBuilder.append(c);
            }
        }
        return stringBuilder.toString();
    }
}
